#include"../include/Dictionary.h"

#include <fstream>
#include <sstream>


using std::ifstream;
using std::istringstream;

void Dictionary::init(const std::string & EnglishDictPath , const std::string & ChineseDictPath ,
            const std::string & EnglishIndexTablePath , const std::string & ChineseIndexTablePath)
{
    _english_dict = Dictionary::getDict(EnglishDictPath);
    _chinese_dict = Dictionary::getDict(ChineseDictPath);
    _english_indexTable = Dictionary::getIndexTable(EnglishIndexTablePath);
    _chinese_indexTable = Dictionary::getIndexTable(ChineseIndexTablePath);
}

std::vector<std::pair<std::string,int>> Dictionary::getDict(const std::string & DictPath)
{
    std::vector<std::pair<std::string,int>> res;
    ifstream ifs(DictPath);
    if(!ifs){
        std::cout << "ifstream open file " << DictPath << " error\n";
        return res;
    }

    std::string line;
    while(getline(ifs,line)){
        std::string vec,num;

        size_t pos = line.find(' ');
        if (pos != std::string::npos) {
            vec = line.substr(0, pos);    //获取单词
            num = line.substr(pos + 1);   //获取频次
        }

        res.push_back({vec,atoi(num.c_str())});
    }

    return res;
}

std::map<std::string,std::set<int>> Dictionary::getIndexTable(const std::string & IndexTablePath)
{
    std::map<std::string,std::set<int>> res;

    ifstream ifs(IndexTablePath);
    if(!ifs){
        std::cout << "ifstream open file " << IndexTablePath << " error\n";
        return res;
    }

    std::string line;
    while(getline(ifs,line)){
        std::string vec;
        std::set<int> linenums;
        size_t pos = line.find(' ');
        if (pos != std::string::npos) {
            vec = line.substr(0, pos);  
            line = line.substr(pos + 1);
            pos = 0;
        }

        while ((pos = line.find(' ', pos)) != std::string::npos) {
            linenums.insert(atoi(line.substr(0, pos).c_str()));
            line = line.substr(pos + 1);
            pos = 0;
        }

        res.insert({vec,linenums});
    }

    return res;
}

std::pair<std::string,int> Dictionary::FindEnglishWord(int line){
    return _english_dict[line-1];
}

std::pair<std::string,int> Dictionary::FindChineseWord(int line){
    return _chinese_dict[line-1];
}

std::set<int> Dictionary::FindEnglishLines(std::string zi){
    std::set<int> empty;
    auto it = _english_indexTable.find(zi);
    if (it != _english_indexTable.end()) {
        return it->second;
    } else {
        return empty;
    }
}

std::set<int> Dictionary::FindChineseLines(std::string zi){
    std::set<int> empty;
    auto it = _chinese_indexTable.find(zi);
    if (it != _chinese_indexTable.end()) {
        return it->second;
    } else {
        return empty;
    }
}